﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Estsh.Core.Base;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Wms.IServices;
using Estsh.Core.Model.Result;
using Estsh.Core.Services;
using Estsh.Core.Repositories;
using Estsh.Core.Models;
using Newtonsoft.Json.Linq;
using static Estsh.Core.Model.EnumUtil.WmsEnumUtil;
using Estsh.Core.Model.EnumUtil;

namespace Estsh.Core.Wms.Services
{
    public class SupplierReturnService : BaseService<BaseEntity>, ISupplierReturnService
    {
        private readonly ISupplierReturnRepository repository;
        private readonly IMoveOrderRepository moveOrderRepository;
        private readonly IStockRepository stockRepository;

        public SupplierReturnService(ISupplierReturnRepository _repository, 
            IMoveOrderRepository _moveOrderRepository, IStockRepository _stockRepository) : base(_repository)
        {
            this.repository = _repository;
            this.moveOrderRepository = _moveOrderRepository;
            this.stockRepository = _stockRepository;
        }

        /// <summary>
        /// 处理扫描的箱条码
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <param name="orderNo"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public string DoCarton(string cartonNo, string orderNo, string loginId)
        {
            SysStock cartonInfo = stockRepository.GetCartonInfo(cartonNo) ;
            
            if (cartonInfo == null)
            {
                return "包装条码不存在，请检查！";
            }
            if (cartonInfo.Enabled.Equals(Enabled.N))
            {
                return "包装条码已被冻结，不允许此操作！";
            }
            if (cartonInfo.Status != (int)StockStatus.NC_INSTOCK&& cartonInfo.Status != (int)StockStatus.RECEIVED && cartonInfo.Status != 180)//不等于nc入库，已收货，质检不合格报错
            {
				// return "包装条码状态不是NC状态，不允许此操作！";
				return "[" + cartonNo + "]：包装条码状态为'" + cartonInfo.StockStatus + "'，不允许此操作！";
			}
            List<WmsMoveDetail> moveDetails = moveOrderRepository.GetMoveDetailList(orderNo);
            WmsMoveDetail? moveDetail = moveDetails.SingleOrDefault(x => x.PartId == cartonInfo.PartId);
            if (moveDetail == null)
            {
                return "此操作单中不包含包装条码对应零件，不允许此操作！";
            }
            if (moveDetail.Qty <= moveDetail.PickQty)
            {
                return "此零件对应的单据数量已满，无法再操作！";
            }
            if (moveDetail.Qty < moveDetail.PickQty + cartonInfo.Qty)
            {
                return "箱包装数量大于单据中此零件的剩余待处理数量！";
            }

            List<WmsMoveSn> moveSns = moveOrderRepository.GetMoveSnList(orderNo);
            List<WmsMoveSn> moveSnCreates = moveSns.Where(x => x.Status == (int)MoveOrderSnStatus.CREATE).ToList();

            WmsMoveSn? moveSn = null;
            if (moveSnCreates != null && moveSnCreates.Count > 0)
            {
                moveSn = moveSnCreates.SingleOrDefault(x => x.CartonNo.Equals(cartonInfo.CartonNo));
                if (moveSn == null)
                {
                    return "单据中不包含此包装条码，不允许此操作！";
                }
            }
            string result = string.Empty;
            if (repository.DoCarton(cartonInfo, moveDetail, moveSn, loginId))
            {
                result = this.SubmitOrderAuto(orderNo, loginId);
            }
            else
            {
                result = "操作失败，请重新尝试！";
            }

            return result;
        }


		/// <summary>
		/// 自动提交单据
		/// </summary>
		/// <param name="orderNo"></param>
		/// <param name="loginId"></param>
		/// <returns></returns>
		public string SubmitOrderAuto(string orderNo, string loginId)
		{
			string result = string.Empty;
			List<WmsMoveDetail> moveDetails = moveOrderRepository.GetMoveDetailList(orderNo);
			var moveDetailsExist = moveDetails.Where(a => a.Qty > a.PickQty).ToList();
			if (moveDetailsExist == null || moveDetailsExist.Count == 0)
			{
				// 完成单据并提交接口
				if (moveOrderRepository.OrderComplete(orderNo, loginId))
				{
					repository.InsertInterfaceBySupplierReturn(orderNo);//添加到接口表
					result = "ORDER_COMPLETED";
				}
				else
				{
					result = "操作失败，请重新尝试！";
				}
			}
			else
			{
				result = "SCAN_OK";
				//提交接口
			}
			return result;
		}


		/// <summary>
		/// 提交单据
		/// </summary>
		/// <param name="orderNo"></param>
		/// <param name="loginId"></param>
		/// <returns></returns>
		public string SubmitOrder(string orderNo,string loginId)
        {
            string result = string.Empty;
            List<WmsMoveDetail> moveDetails = moveOrderRepository.GetMoveDetailList(orderNo);
            var moveDetailsExist = moveDetails.Where(a => a.Qty > a.PickQty).ToList();
            if (moveDetailsExist == null || moveDetailsExist.Count == 0)
            {
                // 完成单据并提交接口
                if (moveOrderRepository.OrderComplete(orderNo, loginId))
                {
                    repository.InsertInterfaceBySupplierReturn(orderNo);//添加到接口表
                    result = "ORDER_COMPLETED";
                }
                else
                {
                    result = "操作失败，请重新尝试！";
                }
            }
            else
            {
                result = "SCAN_NO";
                //提交接口
            }
            return result;
        }

    }
}
